var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var mytoken = require('./token/token');
var jwt = require('express-jwt');
var cors = require('cors');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var goodsRouter = require('./routes/goods');
var reviewsRouter = require('./routes/reviews');
var cartsRouter = require('./routes/carts');
var ordersRouter = require('./routes/orders');

var app = express();

app.use(cors());

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


app.use(jwt.expressjwt({
    secret: 'mall_20250526_xtx',
    algorithms: ['HS256']
}).unless({
    path: ['/users/login', '/users/regist','/goods/lunbo','/goods/all',
        '/goods/catebyid', '/goods/goodslist','/goods/xiaomi','/goods/redmi',
        '/goods/book','/goods/pad','/goods/dianshi','/goods/jiadian','/goods/luyou',
        '/goods/goodsByid', '/reviews/reviewsBygid'
    ]
}));

//解析token获取用户信息
app.use(function(req, res, next) {
    //注意此处token；authorization设置要与设置一致否则可能出现token为空
    var token = req.headers['authorization'];
    if (token == undefined) {
        return next();
    } else {
        mytoken.getToken(token).then((data) => {
            req.data = data; //解析成功后返回设置基本信息（通过req.data判断是否过期）
            return next();
        }).catch((error) => {
            return next();
        })
    }
});
//token失效返回信息
app.use(function(err, req, res, next) {
    if (err.status == 401) {
        //可以设置返回json 形式 
        res.send({ code: 401, msg: 'token失效' })
    }
});

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/goods', goodsRouter);
app.use('/reviews', reviewsRouter);
app.use('/carts', cartsRouter);
app.use('/orders', ordersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    res.send({ code: 404, msg: '找不到请求的url。' })
});

module.exports = app;